import React, { Component } from 'react';
import { Row, Col, Timeline, Card, Button } from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import {routerRedux} from "react-router-dom";
import moment from 'moment';
// import '../../vehicleConfigLogQuery/log.less';

interface bastType {
  key: string;
  value: string;
  type?: number;
}

const bastTop: Array<bastType> = [
//   { key: '协议版本号', value: 'protocolVersion' },
  { key: '设备 VIN', value: 'vin' },
//   { key: '设备 VIN标识', value: 'vinTag' },
//   { key: '消息ID', value: 'msgId' },
  { key: '服务类型', value: 'serviceType' },
  { key: '消息类型', value: 'messageType' },
  { key: '消息发送时间', value: 'timeStamp' },
//   { key: '消息版本号', value: 'msgVersion' },
  { key: '数据长度', value: 'dataLength' },
];
const bastSerial = [{ key: '唯一流水号', value: 'serialNo' }];
class resource_show extends Component<any> {
  state = {
    type: 'requestData',
    otaType: 0,
    itemList: [],
  };

  rightList = {
    // 连接平台下发配置指令
    dcvpRequest: [
      ...bastTop,
      {
        key: '整车OTA远程控制上下电',
        value: 'power',
        type: 1,
        render: (i: number) => {
          return i == 0 ? '下电' : i == 1 ? '上电' : ''
        },
      },
      { key: '整车OTA预约时间', value: 'orderTime', type: 2 },
      ...bastSerial,
    ],
    // tbox回复版本信息
    tboxAnswer: [
      ...bastTop,
      { key: '状态', value: 'status', render: (i: number, item: any) => {
        return i == 0 ? '成功' : i == 1 ? '失败' : ''
      } },
      ...bastSerial,
    ],
    // 连接平台回复版本信息
    dcvpAnswer: [
      { key: '设备vin码', value: 'vin' },
      { key: '回复应答信息时间', value: 'answerTime' },
      { key: '回复应答信息', value: 'answerInfo' },
      ...bastSerial,
    ],
    // tsp下发配置参数
    tboxResult: [
      ...bastTop,
      {
        key: 'OTA远程控制上下电结果',
        value: 'powerResult',
        render: (i: string) => {
          const list = {
            '0': '上电成功',
            '1': '上电失败',
            '2': '车辆已经是上电状态',
            '3': '下电成功',
            '4': '下电失败',
            '5': '车辆已经是下电状态',
          };
          return list[i] || '';
        },
      },
      {
        key: '控制上下电故障列表',
        value: 'powerBreakdown',
        render: (i: string) => {
          const list = {
            '00': '与CCM鉴权失败',
            '01': 'CCM无响应',
            '02': '四门非关闭状态，上电失败',
            '03': '主驾车门未闭锁，上电失败',
            '04': '系统电源不为OFF，上电失败',
            '05': '蓄电池电压不足，上电失败',
            '06': 'CCM反馈OFF>ON切换失败',
            '07': 'CCM反馈ACC>ON切换失败',
            '08': 'CCM反馈当前状态不支持',
            '09': '四门非关闭状态，下电失败',
            '0A': '主驾车门未闭锁，下电失败',
            '0B': '发动机不为远程启动模式',
            '0C': 'CCM反馈ON>OFF切换失败',
          };
          return list[i] || '';
        },
      },
      {
        key: 'OTA安装请求结果',
        value: 'otaResult',
        type: 2,
        render: (i: string) => {
          const list = {
            '0': '请求成功',
            '1': '请求失败',
          };
          return list[i] || '';
        },
      },
      {
        key: 'OTA安装请求故障列表',
        value: 'otaBreakdown',
        type: 2,
        render: (i: string) => {
          const list = {
            '00': 'IVI_UC-Slave报错未接收',
            '01': 'IVI_UC-Master报错未接收',
            '02': '等待IVI_UC-Slave反馈超时',
          };
          return list[i] || '';
        },
      },
      ...bastSerial,
    ],
    // 连接平台下发配置参数
    dcvpResult: [
      ...bastTop,
      { key: '设备vin码', value: 'vin' },
      { key: '回复应答信息时间', value: 'answerTime' },
      { key: '回复应答信息', value: 'answerResult' },
      ...bastSerial,
    ],
    // tbox回复配置结果
    tspConfig: [
      { key: '车辆vin码', value: 'vin' },
      { key: '下发OTA配置参数时间', value: 'configTime' },
      { key: '下发OTA配置参数', value: 'configParam' },
      ...bastSerial,
    ],
    // 连接平台回复配置结果
    dcvpConfig: [
      ...bastTop,
      {
        key: '整车OTA安装请求',
        value: 'installRequest',
        render: (i: number) => {
          const list = {
            0: '无请求',
            1: '有请求（APP端请求立即升级）',
            2: '有请求（服务器端请求静默升级）',
          };
          return list[i] || '';
        },
      },
      ...bastSerial,
    ],
    tboxConfigAnswer: [
      ...bastTop,
      {
        key: '状态',
        value: 'status',
        render: (i: number) => {
          const list = {
            0: '成功',
            1: '失败',
          };
          return list[i] || '';
        },
      },
      ...bastSerial,
    ],
    dcvpConfigAnswer: [
      { key: '车辆VIN码', value: 'vin' },
      { key: '回复配置结果时间', value: 'answerTime' },
      { key: '回复配置结果', value: 'answerInfo' },
      ...bastSerial,
    ],
    tboxConfigResult: [
      ...bastTop,
      {
        key: 'OTA安装请求结果',
        value: 'otaResult',
        render: (i: string) => {
          const list = {
            '0': '请求成功',
            '1': '请求失败',
          };
          return list[i] || '';
        },
      },
      {
        key: 'OTA安装请求故障列表',
        value: 'otaBreakdown',
        render: (i: string) => {
          const list = {
            '00': 'IVI_UC-Slave报错未接收',
            '01': 'IVI_UC-Master报错未接收',
            '02': '等待IVI_UC-Slave反馈超时',
          };
          return list[i] || '';
        },
      },
      ...bastSerial,
    ],
    dcvpConfigResult:[
      { key: '设备vin码', value: 'vin' },
      { key: '回复应答信息时间', value: 'answerTime' },
      { key: '回复应答信息', value: 'answerResult' },
      ...bastSerial,
    ],
    otaResult:[
      { key: '设备vin码', value: 'vin' },
      { key: '推送升级结果时间', value: 'upgradeTime' },
      { key: '推送升级结果', value: 'upgradeResult' },
      ...bastSerial,
    ],
    // TSP下发请求
    requestData: [
      { key: '车辆VIN码', value: 'vin' },
      {
        key: '配置类型',
        value: 'otaType',
        render: (text: number) => {
          const { selectOptions } = this.props;
          const obj = selectOptions.find(e => e.value === text);
          return obj?.label;
        },
      },
      { key: '请求时间', value: 'requestPowerTime' },
      { key: '请求参数', value: 'requestParam' },
      { key: '流水号', value: 'serialNo' },
    ],
    // 下发唤醒短信
    smsData: [
      { key: 'VIN码', value: 'vin' },
      { key: 'SIM卡号', value: 'simNo' },
      { key: '短信内容', value: 'smsContent' },
      { key: '短信发送时间', value: 'smsTime' },
      { key: '短信发送结果', value: 'smsResult' },
    ],
  };
  leftList = [];

  componentDidMount() {
    const { location, id } = this.props;
    const { query } = location || {};
    const newId = query?.id || id;

    if (newId) {
      this.getListFn(newId);
    }
  }
  getListFn = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'OTAConfigLogQueryDetail/getData',
      payload: { url: '/connectLog/otaLogDetail', id },
      callback: (res: any) => {
        const data = res?.data;
        const {
          requestTime,
          requestPowerTime,
          requestParam,
          serialNo,
          simNo,
          smsContent,
          smsTime,
          smsResult,
          vin,
          otaType,
        } = data;
        const list = {};
        const leftList =
          otaType === 1
            ? // 立即升级
              [
                {
                  key: 'requestData',
                  title: 'TSP-->连接平台',
                  p: '下发请求',
                },
                {
                  key: 'smsData',
                  title: '连接平台-->TBOX',
                  p: '下发唤醒短信',
                },
                {
                  key: 'dcvpRequest',
                  title: '连接平台-->TBOX',
                  p: '下发上下电控制指令',
                },
                {
                  key: 'tboxAnswer',
                  title: 'TBOX-->连接平台',
                  p: '回复上下电指令ACK',
                },
                {
                  key: 'dcvpAnswer',
                  title: '连接平台-->TSP',
                  p: '回复应答信息',
                },
                {
                  key: 'tboxResult',
                  title: 'TBOX-->连接平台',
                  p: '回复上下电执行结果',
                },
                {
                  key: 'dcvpResult',
                  title: '连接平台-->TSP',
                  p: '回复上下电执行结果',
                },
                {
                  key: 'tspConfig',
                  title: 'TSP-->连接平台',
                  p: '下发安装控制指令',
                },
                {
                  key: 'dcvpConfig',
                  title: '连接平台-->TBOX',
                  p: '下发安装控制指令',
                },
                {
                  key: 'tboxConfigAnswer',
                  title: 'TBOX-->连接平台',
                  p: '回复安装控制ACK',
                },
                {
                  key: 'dcvpConfigAnswer',
                  title: '连接平台-->TSP',
                  p: '回复安装应答信息',
                },
                {
                  key: 'tboxConfigResult',
                  title: 'TBOX-->连接平台',
                  p: '回复安装执行结果',
                },
                {
                  key: 'dcvpConfigResult',
                  title: '连接平台-->TSP',
                  p: '回复安装执行结果',
                },
                {
                  key: 'otaResult',
                  title: 'OTA平台-->TSP',
                  p: '推送升级结果',
                },
              ]
            : // 预约升级
              [
                {
                  key: 'requestData',
                  title: 'TSP-->连接平台',
                  p: '下发请求',
                },
                {
                  key: 'smsData',
                  title: '连接平台-->TBOX',
                  p: '下发唤醒短信',
                },
                {
                  key: 'dcvpRequest',
                  title: '连接平台-->TBOX',
                  p: '下发预约控制指令',
                },
                {
                  key: 'tboxAnswer',
                  title: 'TBOX-->连接平台',
                  p: '回复预约指令ACK',
                },
                {
                  key: 'dcvpAnswer',
                  title: '连接平台-->TSP',
                  p: '回复预约指令响应结果',
                },

                {
                  key: 'tboxResult',
                  title: 'TBOX-->连接平台',
                  p: '回复执行结果',
                },
                {
                  key: 'dcvpResult',
                  title: '连接平台-->TSP',
                  p: '回复预约执行结果',
                },
                {
                  key: 'otaResult',
                  title: 'OTA平台-->TSP',
                  p: '推送升级结果',
                },
              ];
        let commonData = {
          vin,
          otaType,
          serialNo
        }
        leftList.forEach(e => {
          // 过滤json字符串
          try {
            let obj = JSON.parse(data[e.key]);
            Object.assign(obj, commonData)
            list[e.key] = obj;
          } catch (err) {}
        });
        // 开始2个属性
        Object.assign(list, {
          requestData: {
            // requestTime,
            requestParam,
            requestPowerTime,
            serialNo,
            otaType,
            vin,
          },
          smsData: {
            simNo,
            smsContent,
            smsTime,
            smsResult,
            vin,
          },
        });

        // 赋值 数组
        // 显示那个类型
        this.leftList = leftList;
        this.setState({
          // type: 'requestData',
          itemList: list,
          otaType,
        });
      },
    });
  };
  btnClick = (item: any) => {
    // 修改数据
    // 修改状态
    this.setState({
      type: item.key,
    });
  };
  // 修改状态
  get columnCount() {
    const { type } = this.state;
    // 连接平台下发配置指令、 TBOX回复版本信息
    const arr = ['dcvpRequest', 'tboxVersion', 'dcvpConfig', 'tboxResult'];
    return arr.includes(type);
  }

  getTimeFn = (key: string) => {
    const { itemList } = this.state;
    const el = itemList[key];
    const obj = { ...el?.header, ...el?.body, ...el };
    const arr = Object.keys(obj);
    const i = arr.length
      ? arr.find((e: string) => {
          if (e.search(/time/i) >= 0) {
            return e;
          }
        })
      : '';
    return i && obj[i]
      ? obj[i].indexOf(':') > -1
        ? obj[i]
        : moment(obj[i] * 1000).format('YYYY-MM-DD HH:mm:ss')
      : '';
  };

  goBack = () => {
    const { dispatch } = this.props;
    dispatch(routerRedux.push({ pathname: '/connectPlat/OTAConfigLogQuery', sourcePage: 'OTAConfigLogQueryDetail' }));
  }

  render() {
    const { itemList, type, otaType } = this.state;
    const textFn = item => {
      const el = itemList[type];
      let obj = {}
      if (el) {
        const { header, body, ...rest } = el
        Object.assign(obj, header, body, rest)
      }
      // const obj = Object.assign({}, header, body, ...rest)
      const val = item?.value;
      let str = '';
      if (item?.render) {
        str = item.render(obj[val]);
      } else {
        str = obj[val] || '';
      }
      if (val.search(/time/i) > -1 && obj[val]) {
        obj[val].indexOf(':') > -1
          ? (str = obj[val])
          : (str = moment(obj[val] * 1000).format('YYYY-MM-DD HH:mm:ss'));
      }

      return str;
    };
    return (
      <Card
        style={{ padding: '20px', minWidth: '1200px', height: 'calc(100vh - 112px)' }}
        bodyStyle={{ height: '100%' }}
      >
        <Row justify="space-between" style={{ height: 'calc(100% - 32px)' }}>
          <Col span={7} style={{
            height: '100%',
            paddingTop: '6px',
            paddingRight: '10px',
            overflowX: 'hidden',
            overflowY: 'auto'
          }}>
            <Timeline mode="left">
              {this.leftList.map((item, i) => (
                <Timeline.Item
                  key={item.key}
                  label={this.getTimeFn(item.key)}
                  color={item.key === type ? 'blue' : this.getTimeFn(item.key) ? 'green' : 'gray'}
                >
                  <div onClick={() => this.btnClick(item)}>
                    <p>{item?.title}</p>
                    <p>{item?.p}</p>
                  </div>
                </Timeline.Item>
              ))}
            </Timeline>
          </Col>
          <Col span={16}>
            {type && (
              // ${this.columnCount ? 'desc-flex' : ''}
              <div className={`desc-box `}>
                {this.rightList[type]?.map((item: any) => {
                  // const arr = ['原始报文', '唤醒计数器Cwakeupmax'];
                  //  ${arr.includes(item.key) ? 'flex-3' : ''}
                  return otaType === item?.type || !item?.type ? (
                    <div className={`desc-item`} key={item.key}>
                      <div className="desc-item-fl">{item?.key}</div>
                      <div className="desc-item-fr">{textFn(item)}</div>
                    </div>
                  ) : (
                    ''
                  );
                })}
              </div>
              // <Descriptions bordered column={this.columnCount}>
              //   {this.rightList[type].map((item: any) => (
              //     item.key && <Descriptions.Item
              //       key={item.key}
              //       label={item?.key}
              //       span={item.key === '原始报文' ? 3 : 1}
              //     >
              //       {item.key === '原始报文'? 4 : 1}
              //       {item?.value}
              //     </Descriptions.Item>
              //   ))}
              // </Descriptions>
            )}
          </Col>
        </Row>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Button
            type="primary"
            onClick={() => {
              this.goBack()
              /* if (this.props.onBack) {
                this.props.onBack && this.props.onBack();
                return false;
              }
              router.goBack(); */
            }}
          >
            关闭
          </Button>
        </div>
      </Card>
    );
  }
}
const mapStateToProps = state => {
  const dicData = state?.menu?.dicData || [];
  const selectOptions: Array<any> = [];
  dicData.forEach(e => {
    if (e?.dictCode === 'otaTypeSelect') {
      selectOptions.push({
        value: parseInt(e?.dictKey || 0),
        label: e?.dictValue,
      });
    }
  });
  return { selectOptions };
};
export default connect(mapStateToProps)(resource_show);
